package com.javaweb.dao.impl;

import com.javaweb.dao.CategoryDao;
import com.javaweb.model.Category;
import com.javaweb.service.dto.CategoryDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class CategoryDaoImpl implements CategoryDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    // 根据分类ID删除指定分类
    @Override
    public int deleteCategoryById(String categoryId) {
        String sql = "DELETE FROM tb_category WHERE id = ?";
        return jdbcTemplate.update(sql, categoryId);
    }

    // 新增分类
    @Override
    public int addCategory(CategoryDto categoryDto) {
        String sql = "INSERT INTO tb_category ( name) VALUES ( ?)";
        return jdbcTemplate.update(sql, categoryDto.getName());
    }

    // 获取所有分类
    @Override
    public List<CategoryDto> getAllCategories() {
        String sql = "SELECT * FROM tb_category";
        return jdbcTemplate.query(sql, (rs, rowNum) -> {
            CategoryDto categoryDto = new CategoryDto();
            categoryDto.setId(rs.getString("id"));
            categoryDto.setName(rs.getString("name"));
            return categoryDto;
        });
    }
}
